# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: net_ssl_2_socket_client.py 
@time: 2019/7/17 上午11:40
"""
'''
socket版的双向认证客户端
'''
from socket import socket, AF_INET, SOCK_STREAM
import ssl


class client_ssl:
    def send_hello(self,):
        CA_FILE = "server_cert.pem"
        KEY_FILE = "client_key.pem"
        CERT_FILE = "client_cert.pem"


        context = ssl.SSLContext(ssl.PROTOCOL_TLS)
        context.check_hostname = False
        context.load_cert_chain(certfile=CERT_FILE, keyfile=KEY_FILE)
        context.load_verify_locations(CA_FILE)
        context.verify_mode = ssl.CERT_REQUIRED

        # 与服务端建立socket连接
        with socket() as sock:
            # 将socket打包成SSL socket
            with context.wrap_socket(sock, server_side=False) as sscok:
                sscok.connect(('127.0.0.1', 5678))
                # 向服务发送信息
                msg = "do i connect with server ?".encode('utf-8')
                sscok.send(msg)
                # 接收服务端返回的信息
                msg = sscok.recv(8192).decode('utf-8')
                print(f"receive msg from server : {msg}")
                sscok.close()


if __name__ == '__main__':
    client = client_ssl()
    client.send_hello()